<template>
  <FullPageModal :title="t('aiot.user.add')" :custom-footer="true" @open="open" @cancel="cancel">
    <div class="h-full flex flex-col">
      <div class="flex items-center justify-center mb-8">
        <steps :current="curStep" :data="stepData"> </steps>
      </div>
      <div ref="content" class="flex-1 px-0 md:px-16 lg:px-28 xl:px-36 xxl:px-48 overflow-auto relative">
        <div v-show="curStep === 0">
          <DynamicForm
            ref="userForm"
            :columns="columns"
            :model="userModel"
            :model-form-setting="userModelFormSetting"
            :cur-action="CURDAction.CREATE"
            :force-column="true"
          />
        </div>
        <div v-show="curStep === 1">
          <div class="flex flex-row items-center mb-4">
            <div class="flex-1 text-xl text-color-main">
              <span class="font-semibold align-middle">选择角色</span>
              <span class="text-color-danger ml-1.5 align-middle">*</span>
            </div>
            <div>
              <a-button type="link" @click="addRole"> <Icon type="icon-tianjia" /> 新增角色 </a-button>
            </div>
          </div>
          <a-skeleton v-if="loadingRoleData" active />
          <a-radio-group v-else v-model:value="roleValue" class="block">
            <a-radio
              v-for="(el, i) in roleData"
              :key="el.roleId"
              class="flex flex-row items-center role-radio py-4.5 m-0"
              :class="[i === roleData.length - 1 ? '' : 'border-0 border-b border-solid border-color-split']"
              :value="el.roleId"
            >
              <div class="pl-4.5">
                <div class="text-color-main">{{ el.roleName }}</div>
                <div v-if="el.roleDescription" class="text-color-secondary text-xs mt-2">{{ el.roleDescription }}</div>
              </div>
            </a-radio>
          </a-radio-group>
          <div v-if="rolePanelErrMes" class="mt-2 text-color-danger">{{ rolePanelErrMes }}</div>
        </div>
      </div>
    </div>

    <!-- <div ref="content" class="max-w-284 mx-auto relative">
      <Panel class="mb-7" body-class="pb-0" :title="t('aiot.user.userInfo')">
        <DynamicForm
          ref="userForm"
          :columns="columns"
          :model="userModel"
          :model-form-setting="userModelFormSetting"
          :cur-action="CURDAction.CREATE"
          :force-flex-row="true"
        />
      </Panel>
      <Panel class="mb-7" :title="t('aiot.role.info')" body-class="pb-2" :err-mes="rolePanelErrMes" :required="true">
        <template v-if="!isPlatform" #extraTitle>
          <a href="javascript:void(0)" @click.stop="addRole">
            <Icon type="icon-tianjia" /> {{ t("aiot.role.addRole") }}
          </a>
        </template>
        <SpinSkeleton :loading="loadingRoleData">
          <a-checkbox-group v-model:value="roleValue" style="width: 100%" @change="(roleChange as any)">
            <a-checkbox v-for="el in roleData" :key="el.roleId" :value="el.roleId" class="w-1/2 !m-0 !mb-5">
              <span>{{ el.roleName }}</span>
              <span class="text-sm text-color-secondary ml-2.5">{{ el.roleDescription }}</span>
            </a-checkbox>
          </a-checkbox-group>
        </SpinSkeleton>
      </Panel>
      <Panel :title="t('aiot.role.functionAuth')">
        <AuthList
          v-model:value="authValue"
          :is-update="true"
          :server-value="curRolePermissions"
          :is-admin="isCheckedAdminRole"
        />
      </Panel>
    </div> -->
    <template #footer>
      <template v-if="curStep === 0">
        <a-button @click="cancel">取消</a-button>
        <a-button type="primary" @click="handleContinue">继续</a-button>
      </template>
      <template v-else>
        <a-button @click="handleBack">返回</a-button>
        <a-button @click="ok(false)">确定</a-button>
        <a-button type="primary" @click="ok(true)">确定并继续新增</a-button>
      </template>
    </template>
    <CreateRoleModal
      v-model:visible="roleModalVisible"
      :is-enterprise="!isPlatform"
      :hide-user="true"
      :model="roleModel"
      :model-form-setting="roleModelFormSetting"
      :exclude-role-ids="''"
      @create="onRoleCreate"
    >
    </CreateRoleModal>
    <LocationDialog v-model:visible="locDgVisible" @ok="chooseLoc" />
  </FullPageModal>
</template>
<script lang="ts" setup>
import { useI18n } from "/@/locales/useI18n";
import Panel from "/@/components/Panel.vue";
import { nextTick, ref, shallowRef, watch } from "vue";
import { useCURD } from "/@/hooks/useCURD";
import {
  AdminRoleType,
  AuthorizedRoleFunctionsParams,
  OperPermissionType,
  RoleFunctionMenuItem,
  RoleItem,
  RoleSearchModel,
} from "/@/api/aiot/role/models";
import { Api } from "/@/api/aiot/role";
import { RequestMethodEnum } from "/@/api/req/httpEnum";
import FullPageModal from "/@/components/FullPageModal.vue";
import SpinSkeleton from "/@/components/common/SpinSkeleton.vue";
import { addUser } from "/@/api/aiot/user";
import { CURDAction, DynamicFormExpose } from "/@/components/CURDDialog/models";
import { message, TableColumnProps } from "ant-design-vue";
import { useUserModel } from "./useUserModel";
import type { UseUserModelOptions } from "./useUserModel";
import type { TableRecord } from "/@/api/models";
import CreateRoleModal from "/@/components/pages/Role/CreateRoleModal.vue";
import { useRoleModel } from "../Role/useRoleModel";

const props = defineProps<{
  columns: TableColumnProps<TableRecord>[];
  getOrgData: UseUserModelOptions["getOrgData"];
  isPlatform: boolean;
}>();

const { t } = useI18n();
/**
 * modal
 */
const content = shallowRef<HTMLDivElement>();
const emits = defineEmits(["create", "update:visible"]);
function cancel() {
  emits("update:visible", false);
}
function open(isFirstOpen) {
  if (isFirstOpen) {
    nextTick(() => {
      if (userForm.value) {
        userForm.value.initFormItemComponentData();
      }
    });
  } else {
    //之后每次打开 重置
    reset();
  }
}
function reset() {
  if (userForm.value) {
    userForm.value.resetFields();
  }
  roleValue.value = "";
  // curRolePermissions.value = [];
  rolePanelErrMes.value = "";
  curStep.value = 0;
}
/**
 * steps
 */
const curStep = ref(0);
const stepData = ref([{ title: "用户信息填写" }, { title: "角色选择" }]);
function handleContinue() {
  if (curStep.value === 0) {
    if (userForm.value) {
      userForm.value.validate().then(() => {
        curStep.value++;
      });
    }
  } else {
    curStep.value++;
  }
}
function handleBack() {
  curStep.value--;
}
async function ok(isContinue) {
  if (!roleValue.value) {
    rolePanelErrMes.value = "请选择角色";
    nextTick(() => {
      content.value && (content.value.scrollTop = 9999);
    });
    return;
  }
  const data = { ...userModel.value };
  if (Array.isArray(data.region)) {
    data.region = data.region.join("-");
  }
  // data.roleIds = [roleValue.value];
  data.roleId = roleValue.value;
  if (props.isPlatform) {
    data.companyId = "1";
  }
  // data.userFolderPermissions = authValue.value.roleFolderPermissions || [];
  // data.userMenuPermissions = authValue.value.roleMenuPermissions || [];
  const result = await addUser(data);
  if (result) {
    emits("create");
    message.success(t("common.operSuccess"));
    if (isContinue) {
      reset();
    } else {
      cancel();
    }
  }
}
/**
 * user base info
 */
const { userModel, userModelFormSetting, locDgVisible, chooseLoc, userForm } = useUserModel({
  getOrgData: props.getOrgData,
  isPlatform: props.isPlatform,
  getPopupContainer() {
    return content.value as HTMLElement;
  },
  isCreate: true,
});
/**
 * role
 */
//是否勾选了管理员角色
const isCheckedAdminRole = ref(false);
let loadedRole = false;
watch(curStep, (v) => {
  if (v === 1 && !loadedRole) {
    loadedRole = true;
    reloadRoleData({ roleName: "" });
  }
});
const roleValue = ref("");
watch(roleValue, () => {
  rolePanelErrMes.value = "";
});
// watch(
//   roleValue,
//   (v) => {
//     for (let i = 0; i < v.length; i++) {
//       const roleId = v[i];
//       const roleItem = roleData.value.find((el) => el.roleId === roleId);
//       if (roleItem && (roleItem.roleType === AdminRoleType.system || roleItem.roleType === AdminRoleType.tenant)) {
//         isCheckedAdminRole.value = true;
//         return;
//       }
//     }
//     isCheckedAdminRole.value = false;
//   },
//   { deep: true }
// );
const rolePanelErrMes = ref("");
const {
  tableData: roleData,
  tableLoading: loadingRoleData,
  reloadTable: reloadRoleData,
} = useCURD<RoleItem, RoleSearchModel>({
  getDataUrl: Api.getRolesByName,
  getDataMethod: RequestMethodEnum.POST,
  loadOnMounted: false,
});
// function roleChange(roleIds: string[]) {
//   rolePanelErrMes.value = roleIds.length === 0 ? t("aiot.user.plzSelectOneRole") : "";
//   const selectedRoleData = roleData.value.filter((el) => roleIds.includes(el.roleId as string));
//   //合并权限值
//   const finalPermissions: RoleFunctionMenuItem[] = [];
//   selectedRoleData.forEach((el) => {
//     const rolePermissions: RoleFunctionMenuItem[] = el.rolePermissions ? JSON.parse(el.rolePermissions) : [];
//     rolePermissions.forEach((item) => {
//       if (!item.isFolder) {
//         const target = finalPermissions.find((_item) => _item.functionId === item.functionId);
//         if (target) {
//           //权限已存在
//           if (item.operationsType === OperPermissionType.CHECK) {
//             //查看权限为最低权限 不需再处理
//             return;
//           }
//           target.operationsType = OperPermissionType.MANAGE;
//         } else {
//           finalPermissions.push(item);
//         }
//       }
//     });
//   });
//   curRolePermissions.value = finalPermissions;
// }
/**
 * create role
 */
const roleModalVisible = ref(false);
const { roleModel, roleModelFormSetting } = useRoleModel();
function addRole() {
  roleModalVisible.value = true;
}
function onRoleCreate() {
  reloadRoleData();
}
/**
 * function auth
 */
// const authValue = ref<AuthorizedRoleFunctionsParams>({
//   roleFolderPermissions: [],
//   roleMenuPermissions: [],
// });
// const curRolePermissions = ref<RoleFunctionMenuItem[]>([]);
</script>
<style>
.role-radio > span {
  display: block;
  padding: 0;
}
.role-radio .ant-radio {
  top: 0;
}
</style>
